package com.lancoo.answer.widget.combinationView;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

import com.lancoo.answer.R;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.bean.Item;
import com.lancoo.answer.model.entity.TaskControlBean;
import com.lancoo.answer.util.EditTextInputUtil;
import com.lancoo.answer.util.ExamFontSizeAdjustUtils;
import com.lancoo.answer.util.NetWorkTools;
import com.lancoo.answer.util.SoftInputUtils;
import com.lancoo.answer.util.paperUtils.FragmentCommunicationUtils;
import com.lancoo.answer.widget.WaveView;
import com.rxjava.rxlife.RxLife;
import com.stkouyu.LancooSpeechRecognitionManager;
import com.stkouyu.listener.OnLancooSpeechRecognitionListener;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by pengmi on 2021/12/7 14:18
 * Description:简答题等主观题作答View
 */
public class BriefAnswerView extends RelativeLayout implements View.OnTouchListener{

    private long subTime;
    private static final String TAG = "BriefAnswerView";
    private ImageView img_microphone;
    private WaveView waveView;
    private PopupWindow popupWindow;
    private int childAnswerType=1;
    private int distinguishType=0;//0-识别成英文，1-识别成中文
    private  OnFocusCallBack callBack;
    private int childIndex;


    public BriefAnswerView(Context context) {
        super(context);
        init(context);
    }

    public BriefAnswerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public BriefAnswerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context){
        LayoutInflater.from(context).inflate(R.layout.ev_layout_quese_brief_answer,this);
        findViewById(R.id.img_microphone).setOnTouchListener(this);
        img_microphone = findViewById(R.id.img_microphone);
        adjustFontSize();

    }

    public void setOpenMicroponeAnswer(boolean isOpen){
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        if(taskControlBean!=null&&taskControlBean.isCloseMediaAnswer()){
            img_microphone.setVisibility(GONE);
        }else{
            img_microphone.setVisibility(isOpen?VISIBLE:GONE);
        }

    }

    public void setChildIndex(int childIndex) {
        this.childIndex = childIndex;
    }

    public void intData(Item item, int answerType){
        if(item==null){
            Log.e(TAG,"item is null");
            return;
        }
        EditText edittext = findViewById(R.id.edittext);
        if(item.getStuAnswer()!=null&&!TextUtils.isEmpty(item.getStuAnswer())){
            edittext.setText(item.getStuAnswer());
            edittext.setSelection(item.getStuAnswer().length());
        }
        SoftInputUtils.setEditTextInputSpace(edittext);
        EditTextInputUtil.disableCopyAndPaste(edittext);
        edittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if(callBack!=null){
                    callBack.updateCallBack(edittext.getSelectionStart());
                }
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                item.setStuAnswer(editable.toString().trim());
            }
        });
        edittext.setOnEditorActionListener((v, actionId, event) -> {
            Log.e("edittext","actionId:"+actionId);
            return actionId == 0 && answerType == 2;
        });
        edittext.setOnClickListener(v -> getFocusCallBack(edittext.getSelectionStart()));
        edittext.setOnFocusChangeListener((v, hasFocus) -> {
            if(hasFocus){
                getFocusCallBack(edittext.getSelectionStart());
            }
        });
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        if(taskControlBean!=null&&taskControlBean.getEnableAnwer()==0){//禁止作答
            img_microphone.setEnabled(false);
            edittext.setEnabled(false);
        }
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                subTime= System.currentTimeMillis();
                startRecognition();
                v.getParent().requestDisallowInterceptTouchEvent(true);
                FragmentCommunicationUtils.testEventBus();
                return true;
            case MotionEvent.ACTION_UP:
                if(NetWorkTools.isNetworkConnected(getContext())){
                    boolean isResult= System.currentTimeMillis()-subTime>=200;
                    stopRecognition(isResult);
                }else{
                    stopRecognition(false);
                    Toast.makeText(getContext(),"抱歉，当前网络不可用", Toast.LENGTH_SHORT).show();
                }
                return true;
            case MotionEvent.ACTION_CANCEL:
//                stopRecognition(false);
                return true;
        }
        return false;
    }

    private void startRecognition(){
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED) {
//            Toast.makeText(getApplicationContext(), "没有获取权限,请手动开启权限", Toast.LENGTH_SHORT).show();
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            String[] pressisionArray;
            try {
                pressisionArray = new String[]{Manifest.permission.RECORD_AUDIO};
                Log.e("eeee", "权限不足，请求响应");
                ActivityCompat.requestPermissions( (Activity) getContext(), pressisionArray, 100);//,Manifest.permission.READ_PHONE_STATE
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }
        showRecordPop();
        LancooSpeechRecognitionManager.getInstance(getContext())
                .startSpeechRecognition(distinguishType, new OnLancooSpeechRecognitionListener() {
                    @Override
                    public void onSpeechRecognitionStart() {

                    }

                    @Override
                    public void onSpeechRecogniting(int vad_status, int sound_intensity) {
                        if(waveView==null){
                            return;
                        }
                        Observable.create((ObservableOnSubscribe<Integer>) emitter -> {
                                    emitter.onNext(sound_intensity);
                                })
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .as(RxLife.as(BriefAnswerView.this,true))
                                .subscribe(o -> {
                                    if(waveView!=null){
                                        waveView.setVisibility(View.VISIBLE);
                                        waveView.addData((short)sound_intensity);
                                    }
                                }, throwable -> {});
                    }

                    @Override
                    public void onSpeechRecognitionEnd(String recognitionSentence, String url) {
                        appendAnswer(recognitionSentence);
                    }

                    @Override
                    public void onSpeechRecognitionError(String error) {

                    }
                });
    }

    private void stopRecognition(boolean isEnd){
        LancooSpeechRecognitionManager.getInstance(getContext()).stopSpeechRecognition(isEnd);
        if(popupWindow!=null&&popupWindow.isShowing()){
            popupWindow.dismiss();
        }
    }

    private void appendAnswer(String appendContent){
        if(4==childAnswerType){
            if(!TextUtils.isEmpty(appendContent)){
                boolean isEndEmpty=appendContent.endsWith(" ");
                String substring = appendContent.substring(0, 1);
                String s = substring.toUpperCase();
                String ends=distinguishType==1?"。":".";
                appendContent=s+appendContent.substring(1,appendContent.length()-(isEndEmpty?1:0))+ends;
            }
        }
        Log.e(TAG,"appendAnswer:"+appendContent);
        EditText edittext =findViewById(R.id.edittext);
        Editable text = edittext.getText();
        if(TextUtils.isEmpty(text)){
            edittext.setText(appendContent);
            edittext.setSelection(edittext.getText().length());
        }else{
            int selectionStart = edittext.getSelectionStart();
            if(selectionStart>=0&&selectionStart<text.length()){
                text.insert(selectionStart,appendContent);
                edittext.setText(text);
                edittext.setSelection(selectionStart+appendContent.length());
            }else{
                CharSequence charSequence = text.subSequence(text.length() - 1, text.length());
                if (!TextUtils.equals(" ", charSequence)) {
                    text.append(" ");
                }
                text.append(appendContent);
                edittext.setSelection(text.length());
            }
        }
    }

    private void showRecordPop(){
        @SuppressLint("InflateParams") View inflater= LayoutInflater.from(getContext()).inflate(R.layout.ev_layout_pop_recording,null);
        popupWindow = new PopupWindow(inflater,
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(false);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        popupWindow.showAtLocation(this, Gravity.CENTER,0,0);
        waveView = inflater.findViewById(R.id.waveview);
    }


    public void setChildAnswerType(int answerType){
        this.childAnswerType=answerType;
    }


    public void setDistinguishType(int distinguishType){
        this.distinguishType=distinguishType;
    }

    /**
     * 关闭音频作答
     */
    public void closeAudioAnswer(){
        if(img_microphone==null){
            return;
        }
        img_microphone.setEnabled(false);
        Log.e("eee","简答题已关闭");
        if(popupWindow!=null&&popupWindow.isShowing()){
            LancooSpeechRecognitionManager.getInstance(getContext()).stopSpeechRecognition(true);
            popupWindow.dismiss();
        }

    }

    public void setCallBack(OnFocusCallBack onFocusCallBack){
        this.callBack=onFocusCallBack;
    }

    private void getFocusCallBack(int seletIndex){
        Log.e("briefAnswer","getFocusCallBack:"+seletIndex);
        if(callBack!=null){
            callBack.updateAnswerIndex(childIndex);
        }
    }

    public interface OnFocusCallBack {

        void updateCallBack(int seletIndex);

        void updateAnswerIndex(int childIndex);

    }

    public void requestEditTextFocus(){
        EditText edittext = findViewById(R.id.edittext);
        if(edittext!=null){
            edittext.requestFocus();
        }
    }

    public void setFocusIndex(int selecIndex){
        EditText editText = findViewById(R.id.edittext);
        if(editText==null){
            return;
        }
        editText.setSelection(Math.min(editText.getText().toString().length(), selecIndex));
    }

    public void adjustFontSize(){
        EditText editText = findViewById(R.id.edittext);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(editText,13);
    }

}
